package service

import (
	"dashenwo.com/dashenwo/micro_srv/user_srv/internal/model"
	"dashenwo.com/dashenwo/micro_srv/user_srv/internal/repository"
	"github.com/micro/go-micro/v2/errors"
	"github.com/micro/go-micro/v2/util/log"
)

// 定义用户服务
type UserService struct {
	repo repository.UserRepository
}

// 创建用户服务接口
func NewUserService(repo repository.UserRepository) *UserService {
	return &UserService{
		repo: repo,
	}
}

// 用户登录服务
func (s *UserService) Login(name, pwd string) (*model.User, error) {
	user, err := s.repo.FindByName(name)
	if err != nil {

		return nil, err
	} else if user == nil {
		log.Log("用户信息为", err)
		return nil, nil
	}
	if user.Password != pwd {
		return nil, nil
	}
	return user, nil
}

func (s *UserService) Register(nickname, password, phone, code string) (*model.User, error) {
	// 验证数据
	if nickname == "" {
		return nil, errors.New(
			"com.dashenwo.srv.user.rigister",
			"用户昵称不能为空",
			1001,
		)
	}
	if password == "" {
		return nil, errors.New(
			"com.dashenwo.srv.user.rigister",
			"用户密码不能为空",
			1002,
		)
	}
	if phone == "" {
		return nil, errors.New(
			"com.dashenwo.srv.user.rigister",
			"手机号不能为空",
			1003,
		)
	}
	if code == "" {
		return nil, errors.New(
			"com.dashenwo.srv.user.rigister",
			"手机验证码不能为空",
			1004,
		)
	}
	insetUser := model.User{
		NickName: nickname,
		Password: password,
		Phone:    phone,
	}
	err := s.repo.Add(&insetUser)
	log.Log(insetUser)
	return &insetUser, err
}
